package com.fowo.api.controller.purchase;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.IdPo;
import com.fowo.api.common.model.R;
import com.fowo.api.controller.purchase.dto.productDTO;
import com.fowo.api.controller.purchase.dto.purchaseOrderDealerDTO;
import com.fowo.api.controller.purchase.dto.purchaseOrderDealerDTOList;
import com.fowo.api.entity.PurchaseOrderProduct;
import com.fowo.api.entity.StockInProduct;
import com.fowo.api.mapper.StockInProductExpandMapper;
import com.fowo.api.model.purchase.order.PurchaseOrderVo;
import com.fowo.api.service.PurchaseOrderProductService;
import com.fowo.api.service.PurchaseOrderService;
import com.fowo.api.service.SupplierTrackLogService;
import com.fowo.api.service.impl.PurchaseOrderProductServiceImpl;
import com.fowo.api.service.impl.PurchaseOrderServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/api/purchase-DOrder")
@RestController
public class PurchaseOrderDController {

    @Resource
    private PurchaseOrderServiceImpl purchaseOrderService;

    @Resource
    protected PurchaseOrderProductServiceImpl purchaseOrderProductService;
    @Resource
    protected SupplierTrackLogService supplierTrackLogService;

    @Resource
    private StockInProductExpandMapper stockInProductExpandMapper;

    @Operation(summary = "作废")
    @PostMapping("cancellations")
    public R cancellations(@RequestBody IdListPo po) {
        for(int i=0;i<po.getIds().size();i++){
            Long aLong = po.getIds().get(i);
            try {
                cancellations2(aLong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    @Operation(summary = "新增跟踪日志")
    @PutMapping("updatePurchaseOrderlog")
    public R updatePurchaseOrdelog(@RequestBody PurchaseOrderVo model) throws Exception {
        supplierTrackLogService.saveAllByParentPurchaseOrder(
                model.getId(),
                model.getTrackLog()
        );
        return R.ok(true);
    }

    void cancellations2(Long id) throws Exception {

        PurchaseOrderVo voById = purchaseOrderService.getVoById(id);
        List<PurchaseOrderProduct> list = purchaseOrderProductService.list(Wrappers.<PurchaseOrderProduct>query().lambda().eq(PurchaseOrderProduct::getPurchaseOrderId, voById));
        long count = list.stream().filter(x -> x.getQuantityReceived() != null && x.getQuantityReceived() > 0).count();
        Assert.isTrue(count==0,"已经收货不能作废！");
        //quantityReceived
        if(voById.getQuantityReceived()!=null){
            Assert.isTrue(voById.getQuantityReceived()==0,"已经收货不能作废！");
        }
        voById.setAnStatus("-1");
        purchaseOrderService.updateById(voById);
    }

    @Operation(summary = "结束到货")
    @PostMapping("endDelivery")
    public R endDelivery(@RequestBody IdListPo po) {
        for(int i=0;i<po.getIds().size();i++){
            Long aLong = po.getIds().get(i);
            try {
                endDelivery2(aLong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    void endDelivery2(Long id) throws Exception {

        PurchaseOrderVo voById = purchaseOrderService.getVoById(id);
        Assert.isTrue(voById.getAnStatus().equals("2"),"违规操作！");
//        List<PurchaseOrderProduct> list = purchaseOrderProductService.list(Wrappers.<PurchaseOrderProduct>query().lambda().eq(PurchaseOrderProduct::getPurchaseOrderId, voById));
//        long count = list.stream().filter(x -> x.getQuantityReceived() != null && x.getQuantityReceived() > 0).count();
        voById.setAnStatus("9");
        purchaseOrderService.updateById(voById);
    }

    @Operation(summary = "下单")
    @PostMapping("placeOrder")
    public R placeOrder(@RequestBody IdListPo po) {
        for(int i=0;i<po.getIds().size();i++){
            Long aLong = po.getIds().get(i);
            try {
                placeOrder2(aLong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    void placeOrder2(Long id) throws Exception {
        PurchaseOrderVo voById = purchaseOrderService.getVoById(id);
        Assert.isTrue(voById.getAnStatus().equals("1"),"违规操作！");
        //判断是否填价格了totalPrice
        Assert.isTrue(voById.getTotalPrice()!=null,"请先填写价格！");
        Assert.isTrue(new BigDecimal(voById.getTotalPrice()).compareTo(BigDecimal.ZERO)>0,"请先填写价格！");
        voById.setAnStatus("2");
        voById.setOrderTime(new Date());
        purchaseOrderService.updateById(voById);
    }


    @Operation(summary = "获取价格")
    @PostMapping("getPrice")
    public R getPrice(@RequestBody @Valid purchaseOrderDealerDTO po) {
        //获取仓库的数据
        List<StockInProduct> list=new ArrayList<>();
        for(int i=0;i<po.getIds().size();i++){
            productDTO productDTO = po.getIds().get(i);
            StockInProduct stockInProduct = stockInProductExpandMapper.selectStockInProduct(po.getSupplierId(),productDTO.getProductId());
            if(stockInProduct!=null){
                list.add(stockInProduct);
            }
        }
        return R.data(list);
    }
    @Operation(summary = "获取价格")
    @PostMapping("getPriceList")
    public R getPriceList(@RequestBody @Valid purchaseOrderDealerDTOList po) {
        Page page = po.toPage();
        //获取仓库的数据
        Page<StockInProduct> stockInProduct = stockInProductExpandMapper.
                selectStockInProductList(page,po.getSupplierId(),po.getProductId());
        return R.data(stockInProduct);
    }

}
